package lyxs_916.http_utils;

import android.os.Handler;
import android.webkit.WebView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


/**
 * 类说明:访问网络的线程,加载一个网页
 * Created by 阳 on 2016/9/29
 */

public class HttpUtilWebView extends Thread {
    private String url;
    private Handler handler;
    private WebView webView;

    BufferedReader bufferedReader;

    public HttpUtilWebView(String url, Handler handler, WebView webView) {
        this.url = url;
        this.handler = handler;
        this.webView = webView;
    }

    @Override
    public void run() {
        try {
            //1，把字符串转换成url
            URL httpUrl = new URL(url);
            //2，通过url获取网络连接对象
            HttpURLConnection httpURLConnection = (HttpURLConnection) httpUrl.openConnection();
            httpURLConnection.setReadTimeout(5000);
            httpURLConnection.setRequestMethod("GET");
            //3，获取输入流
            bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
            //4，把输入流内容读取
            final StringBuffer sb = new StringBuffer();
            String str;
            while ((str = bufferedReader.readLine()) != null) {
                sb.append(str);
            }
            //5，post到主线程给view赋值
            handler.post(new Runnable() {
                @Override
                public void run() {
                    webView.loadData(sb.toString(), "text/html;charset=utf-8", null);
                }
            });

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        super.run();
    }
}
